﻿using System.IO;

// ReSharper disable once CheckNamespace
namespace SmartQuant
{
    internal class StreamInstrumentServer : InstrumentServer
    {
        private readonly InstrumentList _instruments = new();
        private string? _path;

        public StreamInstrumentServer() 
            : base(null)
        {
        }

        public override void Close()
        {
        }

        public override void Delete(Instrument instrument)
        {
        }

        public override void Flush()
        {
            if (framework == null || _path == null) 
                return;

            if (File.Exists(_path))
            {
                File.Delete(_path);
            }

            using var stream = File.OpenWrite(_path);
            using var writer = new BinaryWriter(stream);
            foreach (var item in _instruments)
            {
                item.Fields.Clear();
                framework.StreamerManager.Serialize(writer, item);
            }
        }

        public override InstrumentList LoadInstruments()
        {
            if (framework == null || _path == null || !File.Exists(_path))
            {
                return _instruments;
            }
            using var stream = File.OpenRead(_path);
            using var reader = new BinaryReader(stream);
            while (stream.Position < stream.Length)
            {
                var item = framework.StreamerManager.Deserialize(reader);
                switch (item)
                {
                    case Instrument inst:
                        _instruments.Add(inst);
                        break;
                    case DataObject data:
                        //Console.WriteLine($"DataObject: {data.TypeId}");
                        break;
                }
            }

            return _instruments;
        }

        public override void Open()
        {
        }

        public override void Save(Instrument instrument)
        {            
            if (!_instruments.Contains(instrument.Symbol))
            {
                _instruments.Add(instrument.Clone());
            }
        }

        public StreamInstrumentServer SetFramework(Framework framework)
        {
            this.framework = framework;
            return this;
        }

        public void SetDataPath(string path)
        {
            _path = Path.Combine(path, "instrument.bin");
        }
    }
}
